package com.weizhi.business.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.weizhi.server.dto.ResponseDto;
import com.weizhi.server.dto.CategoryDto;
import com.weizhi.server.service.CategoryService;
import com.weizhi.server.util.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("admin/category")
public class CategoryController {

    private final static Logger logger = LoggerFactory.getLogger(CategoryController.class);

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("all")
    public ResponseDto list() {
        logger.info("categoryController-list");
        List<CategoryDto> categoryDtoList = categoryService.all();
        return ResponseDto.createBySuccess(categoryDtoList);
    }

    @RequestMapping("save")
    public ResponseDto save(@RequestBody CategoryDto category) {
        logger.info("categoryController-save, category={}", category);
        /*
            前端进行参数校验：减少无用请求占用服务器资源
            后端进行参数校验：防止用户使用非浏览器进行访问，没有进行参数校验
            后端参数校验失败时不返回具体信息，因为后端校验失败说明是前端校验出bug或者是非浏览器访问
         */

        if(StringUtils.isBlank(category.getName()))
            throw new RuntimeException("请求参数异常");
        categoryService.save(category);
        return ResponseDto.createBySuccess();
    }

    @DeleteMapping("/delete/{id}")
    public ResponseDto delete(@PathVariable Long id) {
        logger.info("categoryController-delete, id={}", id);
        categoryService.delete(id);
        return ResponseDto.createBySuccess();
    }
}

